<template>
    <custom-page-box>
        <div class="success-case-container-update">
            <div class="top">
                <p>{{ !$route.query.id ? '新增' : '编辑' }}案例</p>
                <span>优质案例可以增强客户的信任，提高服务转化</span>
            </div>
            <div class="content">
                <a-form-model
                    ref="ruleForm"
                    :model="form"
                    :rules="rules"
                    :label-col="{ span: 2 }"
                    :wrapper-col="{ span: 16 }"
                >
                    <div class="info-pag">
                        <p class="title">案例基础信息</p>
                        <a-form-model-item label="案例类目" prop="type" class="mt30">
                            <el-cascader
                                v-model="form.type"
                                :options="treeData"
                                placeholder="请选择案例类目"
                                size="small"
                                clearable
                                :props="{ label: 'name', value: 'id', children: 'children', multiple: true }"
                            ></el-cascader>
                            <p class="multiple-tip">多选,最多允许选择10个。如超出10个则只会保存前10个选项。</p>
                        </a-form-model-item>
                        <a-form-model-item label="案例名称" prop="name">
                            <a-input v-model="form.name" placeholder="请填写案例名称" />
                        </a-form-model-item>
                        <a-form-model-item label="案例金额" prop="amount" class="amount">
                            <a-input-number
                                v-model="form.amount"
                                class="amount-input"
                                placeholder="请填写案例金额"
                                :formatter="(value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                                :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"
                            />
                            <span class="ml10">万元</span>
                        </a-form-model-item>
                        <a-form-model-item label="案例封面" prop="img" class="content-img">
                            <p slot="extra" class="tips">
                                支持上传jpe、jpeg、png <br />仅支持上传6张，每张不超过10M，尺寸为400*262
                            </p>
                            <custom-cropper-image
                                :width="400"
                                :height="262"
                                path="case/img"
                                v-model="form.img"
                                :max="6"
                                :fileSize="10"
                                keys="案例封面"
                            ></custom-cropper-image>
                        </a-form-model-item>
                        <a-form-model-item label="案例视频">
                            <p slot="extra" class="tips">仅支持上传一段视频，视频大小不超过50M</p>
                            <custom-video-upload v-model="form.videoList" path="/case/video/"></custom-video-upload>
                        </a-form-model-item>
                        <a-form-model-item label="案例完成时间" prop="date">
                            <a-date-picker
                                v-model="form.date"
                                class="endTime"
                                format="YYYY-MM-DD"
                                valueFormat="YYYY-MM-DD"
                                placeholder="请选择日期"
                                :show-today="false"
                            />
                        </a-form-model-item>
                        <a-form-model-item label="关联服务" prop="contact" class="contact">
                            <a-button @click="getContact">
                                {{ form.contact.map((item) => item.title).join() }}
                                <a-icon type="plus" />
                            </a-button>
                        </a-form-model-item>
                        <a-form-model-item label="案例地址" prop="address" class="address">
                            <!-- <a-button @click="mapShow">
                                {{ form.address || '请选择案例地址' }}
                                <a-icon type="environment" @click="mapShow" />
                            </a-button> -->
                            <a-input readOnly placeholder="请选择案例地址" v-model="form.address">
                                <a-icon slot="suffix" style="color: #009944" type="environment" @click="mapShow" />
                            </a-input>
                        </a-form-model-item>
                    </div>
                    <div class="description-pag">
                        <p class="title">案例正文</p>
                        <a-form-model-item label="案例详情" prop="info" class="content-info mt40">
                            <tinymce-editor v-model="form.info" cosPath="case-richText" :height="400"></tinymce-editor>
                        </a-form-model-item>
                        <a-form-model-item label="案例标签" prop="label" class="content-label">
                            <add-label
                                v-model="form.label"
                                :max="5"
                                :minLabel="2"
                                :maxLength="10"
                                isIcon="plus"
                                :isShow="true"
                            >
                            </add-label>
                        </a-form-model-item>

                        <div class="pl135">
                            <a-form-model-item prop="privacy" class="check-privacy">
                                <a-checkbox v-model="form.privacy">
                                    本人/单位承诺以上内容真实、准确、完整，不侵犯他人合法权益，如因本人/单位上传内容产生纠纷，由本人/单位承担全部责任
                                </a-checkbox>
                            </a-form-model-item>
                            <a-form-model-item>
                                <a-button type="primary" @click="onSubmit"> 上传案例 </a-button>
                            </a-form-model-item>
                        </div>
                    </div>
                </a-form-model>
            </div>
        </div>
        <map-location :isShow="show" @Mapok="handleChange" @hide="hide" :cityInfo="cityInfo" />
    </custom-page-box>
</template>

<script>
import mapLocation from '@/components/map-location/index.vue'
import TinymceEditor from '@/components/tinymce-editor'
import AddLabel from '@/components/add-label'
import { toContactServices } from '@/components/success-case/contact-services'

export default {
    name: 'SuccessCaseUpdate',
    components: {
        TinymceEditor,
        AddLabel,
        mapLocation
    },
    data () {
        const checkPrivacy = (rule, value, callback) => {
            if (value) {
                callback()
            } else {
                callback(new Error('请同意上传协议'))
            }
        }

        // const validatePrice = (rule, value, callback) => {
        //     const { amount } = this.form
        //     if (amount > 9999999999) {
        //         callback(new Error('请勿超过最大值9,999,999,999'))
        //     } else {
        //         callback()
        //     }
        // }
        return {
            form: {
                type: [],
                name: '',
                amount: '',
                img: [],
                videoList: { videoUrl: '', imgCoverUrl: '' },
                date: null,
                contact: [],
                info: '',
                label: [],
                privacy: false,
                address: '',
                lngLat: 'string',
                cityInfo: {
                    address: '',
                    latitude: '',
                    longitude: '',
                    province: '',
                    city: '',
                    area: ''
                }
            },
            treeData: [],
            rules: {
                type: [{ required: true, message: '请选择案例类目', trigger: 'change' }],
                name: [{ required: true, message: '请填写案例名称', trigger: ['blur', 'change'] }],
                // amount: [
                //     { required: true, message: '请填写案例金额', trigger: ['blur', 'change'] },
                //     { validator: validatePrice, trigger: 'change' }
                // ],
                img: [{ type: 'array', required: true, message: '请上传案例封面', trigger: 'change' }],
                info: [{ required: true, message: '请填写案例详情', trigger: 'change' }],
                label: [{ required: true, message: '请添加案例标签', trigger: 'blur' }],
                address: [{ required: true, message: '请选择案例地址' }],
                privacy: [{ required: true, validator: checkPrivacy }]
            },
            show: false
        }
    },
    computed: {
        cityInfo () {
            const { address, latitude, longitude, province, city, area } = this.form.cityInfo
            return { address, latitude, longitude, province, city, area }
        }
    },
    created () {
        this.getTree()
    },
    methods: {
        async getInfo () {
            const res = await this.$ApiServer['case/getInfo']({
                id: this.$route.query.id
            })
            if (res.code === 200) {
                if (res.data) {
                    const {
                        name,
                        serviceKindId,
                        services,
                        photo,
                        amount,
                        detail,
                        finishedTime,
                        label,
                        address,
                        lngLat,
                        area,
                        city,
                        province,
                        videoUrl,
                        imgCoverUrl
                    } = res.data
                    const serviceKindIds = serviceKindId.split(',')
                    const arr = []
                    if (serviceKindIds.length) {
                        serviceKindIds.forEach((id) => {
                            this.treeData.forEach((item) => {
                                item.children.forEach((it) => {
                                    it.children.forEach((i) => {
                                        if (i.id === id) {
                                            arr.push([item.id, it.id, i.id])
                                        }
                                    })
                                })
                            })
                        })
                    }
                    this.form = {
                        type: arr,
                        name,
                        amount,
                        img: photo.split(','),
                        videoList: { videoUrl, imgCoverUrl },
                        date: finishedTime || null,
                        contact: services.map((item) => {
                            return {
                                id: item.serviceId,
                                title: item.service
                            }
                        }),
                        info: detail,
                        label: label.split(',').map((item) => {
                            return {
                                name: item
                            }
                        }),
                        privacy: true,
                        address,
                        cityInfo: {
                            address,
                            latitude: lngLat.split(',')[1],
                            longitude: lngLat.split(',')[0],
                            province,
                            city,
                            area
                        }
                    }
                }
            } else {
                this.$message.error(res.message)
            }
        },
        async getTree () {
            const res = await this.$ApiServer['operationConfig/getTree']()
            if (res.code === 200) {
                const add = (list) => {
                    list.forEach((item) => {
                        item.scopedSlots = { title: 'custom' }
                        if (item.children && item.children.length) {
                            item.children = add(item.children)
                        } else {
                            item.children = undefined
                        }
                    })
                    return list
                }
                this.treeData = add(res.data)
                const filterStatus = (list) => {
                    return list.filter((item) => {
                        if (item.children) {
                            item.children = filterStatus(item.children)
                        }
                        return item.status
                    })
                }
                this.treeData = filterStatus(this.treeData)

                if (this.$route.query.id) {
                    this.getInfo()
                    this.form.privacy = true
                }
            } else {
                this.$message.error(res.message)
            }
        },
        getContact () {
            toContactServices({
                selectList: this.form.contact.map(item => item.id),
                sure: (vm, model) => {
                    this.form.contact = model
                    vm.close()
                }
            })
        },
        onSubmit () {
            this.$refs.ruleForm.validate(async (valid) => {
                if (valid) {
                    const { type, name, amount, img, date, contact, info, label, address } = this.form
                    const { province, city, area } = this.form.cityInfo
                    const { videoUrl, imgCoverUrl } = this.form.videoList
                    const flatten = (arr) => {
                        return [].concat(...arr.map(x => (Array.isArray(x) ? flatten(x) : x)))
                    }
                    const res = await this.$ApiServer['case/update']({
                        id: this.$route.query.id || '',
                        name,
                        serviceKindId: Array.from(new Set(flatten(type.filter((item, index) => index < 10)))).join(','),
                        serviceIdList: contact.map(item => item.id),
                        photo: img.join(),
                        amount,
                        detail: info,
                        finishedTime: date,
                        label: label.map(item => item.name).join(),
                        address,
                        province,
                        city,
                        area,
                        videoUrl,
                        imgCoverUrl,
                        lngLat: [this.cityInfo.latitude, this.cityInfo.longitude].join(',')
                    })
                    if (res.code === 200) {
                        this.$message.success(res.message)
                        this.$router.push('/success-case')
                    } else {
                        this.$message.error(res.message)
                    }
                }
            })
        },
        mapShow () {
            this.show = true
        },
        handleChange (data) {
            this.form.address = data.address
            this.form.cityInfo = {
                address: data.address,
                latitude: data.latitude,
                longitude: data.longitude,
                province: data.province,
                city: data.city,
                area: data.area
            }
            this.show = false
        },
        hide () {
            this.show = false
        }
    }
}
</script>

<style scoped lang="less">
.page-box {
    padding: 0;
}
.mt30 {
    margin-top: 30px;
}
.mt40 {
    margin-top: 40px;
}
.pl135 {
    padding-left: 135px;
}
.ml10 {
    margin-left: 10px;
}
.success-case-container-update {
    .top {
        background: #ddf7e9;
        height: 50px;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        padding-left: 20px;
        p {
            font-size: 16px;
            font-weight: bold;
            color: @primary-color;
            margin-right: 4px;
        }
        span {
            font-size: 12px;
            font-weight: 400;
            color: @primary-color;
        }
    }
    .content {
        padding: 10px;
        .description-pag {
            margin-top: 10px;
        }
        .info-pag,
        .description-pag {
            background: #fff;
            border-radius: 4px;
            padding-bottom: 20px;
            .title {
                padding: 18px 20px 10px;
                border-bottom: 1px solid #f3f3f3;
                font-size: 16px;
                font-weight: 400;
                line-height: 20px;
                color: #333333;
            }
        }
        .amount-input {
            width: 270px;
        }
        .multiple-tip {
            margin-top: 5px;
            font-size: 12px;
            font-weight: 400;
            line-height: 1;
            color: #666;
        }
        ::v-deep {
            .ant-form-item-label {
                width: 135px;
            }
            .ant-form-item-control-wrapper {
                width: 340px;
            }
            .tips {
                font-size: 12px;
                color: #666666;
            }
        }
        .contact {
            button {
                width: 340px;
                position: relative;
                padding-right: 30px;
                text-align: left;
                ::v-deep {
                    span {
                        display: inline-block;
                        width: 100%;
                        overflow: hidden;
                        white-space: nowrap;
                        text-overflow: ellipsis;
                        -o-text-overflow: ellipsis;
                        line-height: 32px;
                    }
                    .anticon {
                        position: absolute;
                        right: 10px;
                        top: 8px;
                        color: @primary-color;
                    }
                }
            }
        }
        .address {
            input {
                width: 340px;
                position: relative;
                padding-right: 30px;
                text-align: left;
                ::v-deep {
                    span {
                        display: inline-block;
                        width: 100%;
                        overflow: hidden;
                        white-space: nowrap;
                        text-overflow: ellipsis;
                        -o-text-overflow: ellipsis;
                        line-height: 32px;
                    }
                    .anticon {
                        position: absolute;
                        right: 10px;
                        top: 8px;
                        color: @primary-color;
                    }
                }
            }
        }
        .endTime {
            width: 100%;
        }
        .content-img {
            ::v-deep {
                .ant-form-item-control-wrapper {
                    width: 700px;
                }
                .ant-upload-select {
                    width: 200px;
                    height: 150px;
                    background: #fff;
                    border: 1px solid #d4d4d4;
                    &:hover {
                        border: 1px solid @primary-color;
                        .anticon {
                            color: @primary-color;
                        }
                        .ant-upload-text {
                            color: @primary-color;
                        }
                    }
                    .anticon {
                        font-size: 42px;
                        color: #999999;
                    }
                    .ant-upload-text {
                        font-size: 14px;
                        color: #999999;
                    }
                }
                .ant-upload-list-picture-card-container {
                    width: 200px;
                    height: 150px;
                }
                .ant-upload-list-picture-card .ant-upload-list-item {
                    width: 200px;
                    height: 150px;
                }
            }
        }
        .content-info {
            ::v-deep {
                .ant-form-item-control-wrapper {
                    width: 700px;
                }
            }
        }
        .content-label {
            ::v-deep {
                .ant-form-item-control-wrapper {
                    width: 700px;
                }
                .ant-btn {
                    width: 110px;
                    color: @primary-color;
                }
            }
        }
        .check-privacy {
            margin-bottom: 5px;
            ::v-deep {
                .ant-form-item-control-wrapper {
                    width: 840px;
                }
                .ant-checkbox-checked .ant-checkbox-inner {
                    background-color: @primary-color;
                    border-color: @primary-color;
                }
            }
        }
    }
}

.content-label ::v-deep {
    .ant-btn {
        height: 32px;
        border-color: #ccc;
    }
    .tips {
        font-size: 12px;
        color: #666;
    }
}
.ant-checkbox-wrapper {
    color: @primary-color;
}
::v-deep {
    .ant-checkbox + span {
        padding-left: 0;
    }
}
</style>
